//Copyright (C) 2009 Ron Coleman. Contact: ronncoleman@gmail.com
//
//This library is free software; you can redistribute it and/or
//modify it under the terms of the GNU General Public License
//as published by the Free Software Foundation; either
//version 3 of the License, or (at your option) any later version.
//
//This library is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
//General Public License for more details.
//
//You should have received a copy of the GNU General Public License
//along with this library; if not, write to the Free Software
//Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA

package org.workplicity.android.cia.ui.mainfragments;

import java.util.Calendar;
import java.util.List;

import org.workplicity.android.cia.R;
import org.workplicity.android.cia.application.ELogApplication;
import org.workplicity.android.cia.ui.ElogEditActivity;
import org.workplicity.android.cia.ui.MainActivity;
import org.workplicity.android.cia.util.CIAHelper;
import org.workplicity.elog.entry.Elog;
import org.workplicity.elog.entry.ElogUser;

import android.app.ListFragment;
import android.content.ClipData;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemLongClickListener;

/**
 * 
 * @author brian.gormanly
 *
 */

public class TitlesFragment extends ListFragment {
    private int mCategory = 0;
    public int mCurPosition = -1;
    private int oldPos = 0;

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        //Current position should survive screen rotations.
        if (savedInstanceState != null) {
            mCategory = savedInstanceState.getInt("category");
            mCurPosition = savedInstanceState.getInt("listPosition");
        }

        populateTitles();
        ListView lv = getListView();
        lv.setChoiceMode(AbsListView.CHOICE_MODE_SINGLE);
        lv.setCacheColorHint(Color.TRANSPARENT);
        lv.setOnItemLongClickListener(new OnItemLongClickListener() {
            @Override
			public boolean onItemLongClick(AdapterView<?> av, View v, int pos, long id) {
            	// get the selected elog
            	MainActivity myActivity = (MainActivity)getActivity();

            	myActivity.getApp().setCurrentElog(myActivity.getApp().getAllElogs().get(pos));
            	ContentFragment frag = (ContentFragment) getFragmentManager().findFragmentById(R.id.frag_content);
            	frag.refresh();
            	
                updateImage(pos);
                
                Intent myIntent = new Intent(myActivity, ElogEditActivity.class);
                startActivityForResult(myIntent, 0);
				return true;
            }
        });

        selectPosition(mCurPosition);
    }

    private class MyDragShadowBuilder extends View.DragShadowBuilder {
        private Drawable mShadow;

        public MyDragShadowBuilder(View v) {
            super(v);

            final TypedArray a = v.getContext().obtainStyledAttributes(R.styleable.AppTheme);
            mShadow = a.getDrawable(R.styleable.AppTheme_listDragShadowBackground);
            mShadow.setCallback(v);
            mShadow.setBounds(0, 0, v.getWidth(), v.getHeight());
            a.recycle();
        }

        @Override
        public void onDrawShadow(Canvas canvas) {
            super.onDrawShadow(canvas);
            mShadow.draw(canvas);
            getView().draw(canvas);
        }
    }

    public void populateTitles() {

    	try {
	    	MainActivity myActivity = (MainActivity)getActivity();
	    	
	    	// intialize array of choices
	    	String[] choices;
	    	
	    	if(myActivity.getApp().getAllElogs().size() > 0) {
	    		choices = new String[myActivity.getApp().getAllElogs().size()];
	    	}
	    	else {
	    		choices = new String[1];
	    	}
	    	
	    	// get the resourcess available
	        Resources res = getResources();
	
	    	// worklogs
	    	// Get the string array that has the tabs / names
	        //choices = res.getStringArray(R.array.workorders_array);
	
	    	choices[0] = getString(R.string.NoData);
	    	
	    	Elog log = null;
	    	Elog.Type[] types = new Elog.Type[myActivity.getApp().getAllElogs().size()];
			Elog.Status[] statuses = new Elog.Status[myActivity.getApp().getAllElogs().size()];
			Boolean[] isRecent = new Boolean[myActivity.getApp().getAllElogs().size()];
	    	
	    	for(int i=0; i<myActivity.getApp().getAllElogs().size(); i++) {
	    		log = myActivity.getApp().getAllElogs().get(i);
	    		
	    		Calendar cal = Calendar.getInstance();
	    		cal.setTimeInMillis(log.getUpdateDate().getTime());
	    		
	    		ElogUser thisUser = myActivity.getApp().getUserById(log.getUpdateUserId());
			
	    		choices[i] = "Id: " + log.getId() + "\n" +
	    			"Updated: " + CIAHelper.asDate(cal) + " " + CIAHelper.asTime(log.getUpdateDate()) + "\n" +
	    			"By: " + thisUser.getFirstName().toString() + " " + thisUser.getLastName().toString() + "\n" +
	    			"Status: " + log.getStatus();
	    		
	        	types[i] = log.getType();
	        	statuses[i] = log.getStatus();
	        	isRecent[i] = CIAHelper.isRecent(log);
	
	    	}
	            
	
	    	// set list adapter will go here
	    	setListAdapter(new MyAdapter(myActivity, choices, statuses, types, isRecent));
    	}
    	catch(Exception e) {
    		
    	}
        
    }
    
    
    private class MyAdapter extends ArrayAdapter<String> {
    	
    	String[] names;
    	Elog.Status[] status;
    	Elog.Type[] type;
    	Boolean[] isRecent;
    	 
        public MyAdapter(Context context, String[] names, Elog.Status[] statuses, Elog.Type[] types, Boolean[] isRecent) {
            super(context, R.layout.title_list_item, R.id.listResource, names);
            
            this.names = names;
            if(statuses != null) {
            	this.status = statuses;  	
            }
            if(types != null) {
            	this.type = types;
            }
            if(isRecent != null) {
            	this.isRecent = isRecent;
            }
        }
 
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            
        	LayoutInflater mInflater = (LayoutInflater)getActivity().getLayoutInflater();
        	
        	View row;
        	 
        	if (null == convertView) {
        		row = mInflater.inflate(R.layout.title_list_item, null);
        	} else {
        		row = convertView;
        	}
        	
        	//TextView tv = (TextView) row.findViewById(android.R.id.text1);
        	TextView tv = (TextView)super.getView(position, convertView, parent);

        	tv.setText(names[position]);
        	
        	try {
        		
        		if(this.isRecent[position] == true) {
        			tv.setBackgroundResource(R.color.green);
        		}
        		else if(this.type[position] == Elog.Type.UNUSUAL) {
	        		tv.setBackgroundResource(R.color.orange);
	        	}
	        	else if(this.type[position] == Elog.Type.SUMMARY) {
	        		tv.setBackgroundResource(R.color.purple);
	        	}
	        	else {
	        		tv.setBackgroundResource(R.color.white);
	        	}
        		
        		if(mCurPosition > -1 && position == mCurPosition){
        			tv.setTypeface(null, Typeface.BOLD);

        		}
        		else {
        			tv.setTypeface(null, Typeface.NORMAL);

        		}
	        	
        	}
        	catch(Exception e) {
        		
        	}
        	 
        	
        	return tv;

        }
 
    }

    @Override
    public void onListItemClick(ListView l, View v, int position, long id) {
    	// get the selected elog
    	MainActivity myActivity = (MainActivity)getActivity();

    	myActivity.getApp().setCurrentElog(myActivity.getApp().getAllElogs().get(position));
    	ContentFragment frag = (ContentFragment) getFragmentManager().findFragmentById(R.id.frag_content);
    	frag.refresh();
    	

        updateImage(position);
    }
    
    private void updateImage(int position) {
        ContentFragment frag = (ContentFragment) getFragmentManager().findFragmentById(R.id.frag_content);
        frag.updateContentAndRecycleBitmap(mCategory, position);
        
        mCurPosition = position;
    }

    public void selectPosition(int position) {
        ListView lv = getListView();
        lv.setItemChecked(position, true);
        updateImage(position);
    }

    @Override
    public void onSaveInstanceState (Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putInt("listPosition", mCurPosition);
        outState.putInt("category", mCategory);
    }
}
